#!/usr/bin/python3

import multiprocessing
from telnetlib import Telnet
from finalqytclearLine import routerclearline
from finalqytclearrouter import clearrouter
from finalqytclearsw import clearsw
from finalqytclearasa import clearasa
import time
import os

devices = {1:'R1', 2:'R2', 3:'R3', 4:'R4', 5:'R5', 6:'R6', 7:'ASA1', 8:'ASA2',
           9:'ASA3', 10:'ASA4', 11:'SW1', 12:'SW2', 13:'SW3', 14:'SW4', 15:'SW5', 16:'SW6'}
        

def clearrack(username, password, rackno):

    result = 1

	index = []
	for i in range(16):
		index.append(1)
	processes = []

	clearlinemp = multiprocessing.Process(target=routerclearline, args=(username, password, rackno))
	clearlinemp.start()
	time.sleep(10)
	for i in range(6):
		newri = i + 1
		clearroutermp = multiprocessing.Process(target=clearrouter, args=(username, password, rackno, newri))
		processes.append(clearroutermp)
		clearroutermp.start()

	for i in range(4):
		newai = i + 1
		clearasamp = multiprocessing.Process(target=clearasa, args=(username, password, rackno, newai))
		processes.append(clearasamp)
		clearasamp.start()

	for i in range(6):
		newsi = i + 1
		clearswmp = multiprocessing.Process(target=clearsw, args=(username, password, rackno, newsi))
		processes.append(clearswmp)
		clearswmp.start()

	clock1 = time.clock()

	while True:
		os.system('clear')
		allDone = index.count(0)
		clock2 = time.clock()
		timetouse = int((clock2 - clock1) * 1000)
		stringtimetouse = str(timetouse)
		print('Use time: ' + stringtimetouse)
		if timetouse > 260:
			print('Timeout')
			for i in range(16):
				processes[i].terminate()
			result = 0
			break
		if allDone == 16:
			print('ALL DONE!!!!!!')
			break
		for i in range(16):
			if processes[i].exitcode == 0: 
				index[i] = 0
				print('%s done' % devices[i+1])
			else:
				print('%s clearing' % devices[i+1])
		time.sleep(3)

	if result == 0:
		print("run again for reconfirm")
		clearrack(yourname, yourpw, rackno)
	
if __name__ == "__main__":
	import getpass
	yourname = input('your username: ')
	yourpw = getpass.getpass('your password: ')
	print('Serious attention the Rack is in you control')
	print('BJRack01 or BJRack02 or BJRack03')
	rackno1 = input('The Rack you want to clear: ')
	rackno2 = input('Reconfirm the Rack: ')
	if rackno1 == rackno2:
		rackno = rackno1
		clearrack(yourname, yourpw, rackno)
	else:
		print('rackno missmatch')